from flask import Flask, render_template, request, redirect, url_for, session, flash
import os
import random
import time

app = Flask(__name__)
app.secret_key = os.urandom(24)

# 模拟用户数据库
users = {
    "admin": "password123",
    "user": "mypassword"
}

# 模拟手机号数据库
phone_users = {
    "13812345678": "admin"
}

# 存储验证码的字典（实际项目中应使用Redis等缓存）
verification_codes = {}

def generate_verification_code():
    """生成6位随机验证码"""
    return str(random.randint(100000, 999999))

def send_verification_code(phone):
    """模拟发送验证码（实际项目中应调用短信服务）"""
    code = generate_verification_code()
    # 在实际应用中，这里应该调用短信服务API发送验证码
    verification_codes[phone] = {
        'code': code,
        'timestamp': time.time()
    }
    print(f"验证码已发送到 {phone}: {code}")  # 仅用于测试，实际项目中应删除
    return code

def verify_code(phone, code):
    """验证手机号和验证码"""
    if phone in verification_codes:
        stored_code = verification_codes[phone]
        # 检查验证码是否正确且未过期（5分钟内有效）
        if stored_code['code'] == code and time.time() - stored_code['timestamp'] < 300:
            return True
    return False

@app.route('/')
def home():
    if 'username' in session:
        return render_template('home.html', username=session['username'])
    return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        login_type = request.form.get('login_type', 'username')
        
        if login_type == 'username':
            # 用户名密码登录
            username = request.form['username']
            password = request.form['password']
            
            if username in users and users[username] == password:
                session['username'] = username
                flash('登录成功!', 'success')
                return redirect(url_for('home'))
            else:
                flash('用户名或密码错误', 'error')
        
        elif login_type == 'phone':
            # 手机号验证码登录
            phone = request.form['phone']
            code = request.form['code']
            
            if verify_code(phone, code):
                # 验证成功，获取对应用户名
                if phone in phone_users:
                    username = phone_users[phone]
                    session['username'] = username
                    flash('登录成功!', 'success')
                    return redirect(url_for('home'))
                else:
                    flash('该手机号未注册', 'error')
            else:
                flash('验证码错误或已过期', 'error')
    
    return render_template('login.html')

@app.route('/send_code', methods=['POST'])
def send_code():
    """发送验证码接口"""
    phone = request.form.get('phone')
    if phone:
        # 简单验证手机号格式
        if len(phone) == 11 and phone.startswith('1'):
            send_verification_code(phone)
            return {'success': True, 'message': '验证码已发送'}
        else:
            return {'success': False, 'message': '手机号格式不正确'}
    return {'success': False, 'message': '手机号不能为空'}

@app.route('/logout')
def logout():
    session.pop('username', None)
    flash('您已成功登出', 'info')
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(debug=True)